package action;

import Impl.UserDaoImpl;
import entity.User;
import service.LoginService;
import service.LoginServiceImpl;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class LoginAction extends HttpServlet {

	private static final long serialVersionUID = 2149515480031549266L;
	
	private LoginService service = new LoginServiceImpl();

	
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println("-------正在执行LoginAction---------");
		// 用户提交的手机或邮箱
		String uid = request.getParameter("name");
		// 用户的个人密码
		String pwd = request.getParameter("password");

		
		if(!service.isNormalCode(request)){
			request.setAttribute("message", "验证码不正确！");
			request.getRequestDispatcher("/login.jsp").forward(request, response);
			return;
		}

		UserDaoImpl userDao = new UserDaoImpl();
		User user = userDao.getUserByCondition(uid);
//		判断
		if (user==null||!user.getPassword().equals(pwd)){
			request.setAttribute("message", "用户名或密码错误！");
			request.getRequestDispatcher("/login.jsp").forward(request, response);
			return;
		}
		HttpSession session =request.getSession();
		System.out.println("登录成功！");
		session.setAttribute("user",user);
		session.setAttribute("uname",user.getName());
		request.getRequestDispatcher("/header.jsp").forward(request,response);
	}
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
